package com.seuic.hnapps.device_implement;

import android.os.RemoteException;
import android.util.Log;

import com.seuic.hnapps.posdsdk.device_interface.PsamDevice;
import com.seuic.hnapps.util.HexUtil;


public class PsamDeviceImp extends BaseImplement implements PsamDevice {


    private static PsamDeviceImp self;

    private PsamDeviceImp() {
    }

    static PsamDeviceImp getInstance() {
        if ( self == null ) {
            synchronized ( PsamDeviceImp.class ) {
                if ( self == null ) {
                    self = new PsamDeviceImp();
                }
            }
        }
        return self;
    }

    @Override
    public String open() {
        if (psamReader == null) {
            setLastError( "Service Error" );
            return null;
        }
        byte[] atr = new byte[256];
        int[] atr_len = new int[1];
        int result;
        try {
            result = psamReader.open( (byte)0, 2, atr, atr_len );
        } catch (RemoteException e) {
            setLastError( "Service RemoteException: " + e );
            return null;
        }
        if ( result < 0 ) {
            setLastError( "Service Execution Error" );
            return null;
        } else {
            Log.i( LOG_TAG, "atr:" + HexUtil.byteToHexString(atr, atr_len[0]) );
            return HexUtil.byteToHexString(atr, atr_len[0]);
        }
    }

    @Override
    public void close() {
        if (psamReader == null) {
            setLastError( "Service Error" );
            return;
        }
        try {
            psamReader.close();
        } catch (RemoteException e) {
            setLastError( "Service RemoteException: " + e );
        }
    }

    @Override
    public String exchangeApdu(String apdu) {
        if (psamReader == null) {
            setLastError( "Service Error" );
            return null;
        }
        if ( apdu == null ) {
            setLastError( "Input Param Error" );
            return null;
        }
        byte[] rsp_byte;
        try {
            rsp_byte = psamReader.exchangeApdu( HexUtil.hexStringToByteArray( apdu ) );
        } catch (RemoteException e) {
            setLastError( "Service RemoteException: " + e );
            return null;
        }
        if ( rsp_byte == null ) {
            return null;
        }
        return HexUtil.byteToHexString( rsp_byte );
    }
}
